package com.wwj.core.wawa.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.wwj.core.wawa.entity.Room;
import com.wwj.core.wawa.entity.WaWaMachine;
import com.wwj.core.wawa.entity.mapper.WaWaMachineMapper;
import com.wwj.core.wawa.service.IRoomService;
import com.wwj.core.wawa.service.IWaWaMachineService;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
public class WaWaMachineServiceImpl implements IWaWaMachineService {

    @Resource
    private WaWaMachineMapper waWaMachineMapper;

    @Resource
    private IRoomService roomService;

    @Override
    public WaWaMachine findByDeviceId(String deviceId) throws Exception {
        Map<String, Object> param = new HashMap<String, Object>();
        param.put("deviceId", deviceId);
        List<WaWaMachine> list = waWaMachineMapper.selectByParam(param);
        return list != null && list.size() > 0 ? list.get(0) : null;
    }

    @Override
    public int createNewMachine(WaWaMachine waWaMachine) throws Exception {
        waWaMachine.setCreateTime(Calendar.getInstance().getTime());
        waWaMachineMapper.save(waWaMachine);
        Room room = new Room();
        room.setWawaMachineId(waWaMachine.getId());
        roomService.createRoom(room);
        return 1;
    }

    @Override
    public int updateMachine(WaWaMachine waWaMachine) throws Exception {
        waWaMachine.setUpdateTime(Calendar.getInstance().getTime());
        return waWaMachineMapper.update(waWaMachine);
    }

    @Override
    public List<WaWaMachine> findAll() throws Exception {
        return waWaMachineMapper.selectByParam(null);
    }

    @Override
    public Page<WaWaMachine> findByPage(Map<String,Object> params,int offset, int limit) throws Exception {
        PageHelper.offsetPage(offset, limit);
        return (Page<WaWaMachine>)waWaMachineMapper.findByPage(params);
    }
}
